package com.gcsoftware.gw.xml;


import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.StringReader;
import java.io.StringWriter;

/**
 * Created by qs on 2018/4/10.
 */
public class GwXmlUtil {
    public static <T> String createXML(Class<T> entityClass, Object entity) {
        StringWriter writer = new StringWriter();
        try {
            JAXBContext act = JAXBContext.newInstance(entityClass);
            Marshaller marshaller = act.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
            marshaller.marshal(entity, writer);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return writer.toString();
    }

    public static <T> Object createObject(Class<T> entityClass, String entity) {
        Object object = null;
        try {
            JAXBContext act = JAXBContext.newInstance(entityClass);
            Unmarshaller unMarshaller = act.createUnmarshaller();
            object = unMarshaller.unmarshal(new StringReader(entity));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return object;
    }
}
